package com.exthirteen.textgamescript.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;

/**
 * <p>
 * jackson工具类
 * </p>
 *
 * @author exthirteen
 * @since 2022/4/21
 */
@Component
@Order(1)
public class JacksonUtil implements ApplicationRunner {

    private static ObjectMapper jackson;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        JacksonUtil.jackson = SpringContextUtil.getApplicationContext().getBean(ObjectMapper.class);
    }

    /**
     * 转JSON字符串
     * @param object 对象
     * @return JSON字符串
     */
    public static String toJsonString(Object object){
        try {
            String json = jackson.writeValueAsString(object);
            return "null".equals(json) ? null : json;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * JSON字符串转JavaBean
     * @param content json
     * @param valueType 类型
     * @param <T> 泛型
     * @return 实例化后的Bean
     */
    public static <T> T toJavaBean(String content, Class<T> valueType){
        try {
            return jackson.readValue(content,valueType);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * JSON字符串转JavaBean
     * @param content json
     * @param valueTypeRef 自定义类型
     * @param <T> 泛型
     * @return 实例化后的Bean
     */
    public static <T> T toJavaBean(String content, TypeReference<T> valueTypeRef){
        try {
            return jackson.readValue(content, valueTypeRef);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * JSON字符串转JavaBean
     * @param content json
     * @param type type
     * @param <T> 泛型
     * @return 实例化后的Bean
     */
    public static <T> T toJavaBean(String content, Type type){
        try {
            return jackson.readValue(content, jackson.constructType(type));
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}
